package top.codechap.extension;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.*;
import org.springframework.stereotype.Component;
import top.codechap.extension.model.Black;
import top.codechap.ioc.framework.beans.factory.support.BeanDefinitionReader;

import java.util.Arrays;

/**
 * @author CodeChap
 * @date 2021-06-26 21:26
 * @description MyBeanDefinitionRegistryPostProcessor
 */
@Component
public class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {

    // BeanDefinitionRegistry 是Bean定义信息的保存中心, 以后BeanFactory就是按照BeanDefinitionRegistry里面保存的每一个bean定义信息来创建bean实例
    // 因此可以手动在BeanDefinitionRegistry 中添加bean信息
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        System.out.println("MyBeanDefinitionRegistryPostProcessor...执行了postProcessBeanDefinitionRegistry()");
        int count = registry.getBeanDefinitionCount();
        System.out.println("当前的BeanFactory中有Bean的个数为count = " + count);
        // 手动给BeanDefinitionRegistry 中添加bean信息(Black对象)
        // registerBeanDefinition() 方法中需要传入bean名称和bean的BeanDefinition对象,因此需要new一个BeanDefinition对象
        // new一个BeanDefinition对象: 方式一
        RootBeanDefinition newBeanDefinition = new RootBeanDefinition(Black.class);
        // new一个BeanDefinition对象: 方式二
//        AbstractBeanDefinition newBeanDefinition = BeanDefinitionBuilder.rootBeanDefinition(Black.class).getBeanDefinition();
        registry.registerBeanDefinition("newBean",newBeanDefinition);
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        System.out.println("MyBeanDefinitionRegistryPostProcessor...执行了postProcessBeanFactory()");
        int count = beanFactory.getBeanDefinitionCount();
        System.out.println("当前的BeanFactory中有Bean的个数为count = " + count);
        String[] names = beanFactory.getBeanDefinitionNames();
        System.out.println(Arrays.asList(names));
    }
}
